package com.qunar.qcf.core.service;

import java.io.IOException;

import com.qunar.qcf.core.session.IdleStatus;
import com.qunar.qcf.core.session.IoSession;

/**
 * Handles all I/O events fired by MINA.
 *
 * @see IoHandlerAdapter
 * mina中所有I/O事件都是由这个接口来负责处理的
 * 这些事件都是由IoProcessor发出来的,同一个IoProcessor线程负责处理多个会话
 */
public interface IoHandler {
    /**
     * 会话创建后调用此方法
     * Invoked from an I/O processor thread when a new connection has been created.
     * Because this method is supposed to be called from the same thread that
     * handles I/O of multiple sessions, please implement this method to perform
     * tasks that consumes minimal amount of time such as socket parameter
     * and user-defined session attribute initialization.
     */
    void sessionCreated(IoSession session) throws Exception;

    /**
     * 打开会话，与sessionCreated最大的区别就是它是从另外一个线程处调用的
     * Invoked when a connection has been opened.  This method is invoked after
     * {@link #sessionCreated(IoSession)}.  The biggest difference from
     * {@link #sessionCreated(IoSession)} is that it's invoked from other thread
     * than an I/O processor thread once thread model is configured properly.
     */
    void sessionOpened(IoSession session) throws Exception;

    /**
     * 会话结束，当连接被关闭时调用
     * Invoked when a connection is closed.
     */
    void sessionClosed(IoSession session) throws Exception;

    /**
     * 会话空闲时调用
     * Invoked with the related {@link IdleStatus} when a connection becomes idle.
     * This method is not invoked if the transport type is UDP; it's a known bug,
     * and will be fixed in 2.0.
     */
    void sessionIdle(IoSession session, IdleStatus status) throws Exception;

    /**
     * 异常捕获 mina会自动关闭此连接
     * Invoked when any exception is thrown by user {@link IoHandler}
     * implementation or by MINA.  If <code>cause</code> is an instance of
     * {@link IOException}, MINA will close the connection automatically.
     */
    void exceptionCaught(IoSession session, Throwable cause) throws Exception;

    /**
     * 处理接收消息
     * Invoked when a message is received.
     */
    void messageReceived(IoSession session, Object message) throws Exception;

    /**
     * 在消息发送后触发
     * Invoked when a message written by {@link IoSession#write(Object)} is
     * sent out.
     */
    void messageSent(IoSession session, Object message) throws Exception;
}